<template>
  <div class="loginPage">
    {{ userStore.uid }}
    <el-form
      :model="Loginform"
      label-width="90px"
      class="Loginform"
      :rules="rules"
    >
      <h2>莱头条管理系统</h2>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="Loginform.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="Loginform.password" type="password" />
      </el-form-item>
      <el-button type="primary" size="large" style="width: 80%" @click="login"
        >登陆</el-button
      >
    </el-form>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import { doLogin } from "@/api/login";
import { ElMessage } from "element-plus";
import useUserStore from "@/store/user";

const userStore = useUserStore();

console.log(userStore.uid);

const Loginform = reactive({
  username: "",
  password: "",
});

function validateUsername() {
  return /^\w{6,16}$/.test(Loginform.username);
}
function validatePassword() {
  return /^\w{6,16}$/.test(Loginform.password);
}

const rules = reactive({
  username: [
    { required: true, message: "请填写用户名", trigger: "blur" },
    {
      validator: validateUsername,
      trigger: "change",
      message: "用户名为6-16位字母数字",
    },
  ],
  password: [
    { required: true, message: "请填写密码", trigger: "blur" },
    {
      validator: validatePassword,
      trigger: "change",
      message: "密码为6-16位字母数字",
    },
  ],
});

function login() {
  let { username, password } = Loginform;

  doLogin({
    username,
    password,
  })
    .then((res) => {
      console.log(res);
      if (res.code == 0) {
        ElMessage({
          message: "登陆成功",
          type: "success",
        });

        let { token, tokenExpired, userInfo ,uid} = res;

        localStorage.setItem("token", token);
        localStorage.setItem("tokenExpired", tokenExpired);

        //  把数据存到pinia

        userStore.changeUserId(uid);
        userStore.changeUserInfo(userInfo);
        ///  路由跳转
      } else {
        ElMessage({
          message: "登陆失败",
          type: "error",
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
}
</script>

<style>
.loginPage {
  width: 100%;
  height: 100vh;
  background-color: darkslategray;
  text-align: center;
  padding-top: 20vh;
}

.Loginform {
  width: 400px;
  margin: 0 auto 0;
  padding: 20px 40px 40px;
  background-color: aliceblue;
}
.Loginform h2 {
  margin-bottom: 50px;
}
</style>
